<template>
  <div>
    <custom-container
      ref="customContainerRef"
      :config="mianConfig"
      :model-value="modelValue"
      @update:modelValue="modelValue = $event"
    ></custom-container>
    <!-- 添加或修改参数配置对话框 -->
    <setForm
      ref="setFormRef"
      v-model:open="open"
      v-model:title="title"
      @changeList="handleQuery"
    />
    <!-- 任务日志详细 -->
    <el-dialog
      v-model="openView"
      title="任务详细"
      width="800px"
      append-to-body
    >
      <el-form :model="formDetail" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务编号：" :label-position="labelPosition">{{ formDetail.jobId }}</el-form-item>
            <el-form-item label="任务名称：" :label-position="labelPosition">{{ formDetail.jobName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组：" :label-position="labelPosition">{{ jobGroupFormat(formDetail) }}</el-form-item>
            <el-form-item label="创建时间：" :label-position="labelPosition">{{ formDetail.createTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="cron表达式：" :label-position="labelPosition">{{ formDetail.cronExpression }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次执行时间：" :label-position="labelPosition">{{ formDetail.nextValidTime }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调用目标方法：" :label-position="labelPosition">{{ formDetail.invokeTarget }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务状态：" :label-position="labelPosition">
              {{ jobStatusFormat(formDetail) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否并发：" :label-position="labelPosition">
              {{ jobConcurrentFormat(formDetail) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行策略：" :label-position="labelPosition">
              {{ jobMisfirePolicyFormat(formDetail) }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openView = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, defineAsyncComponent, getCurrentInstance } from 'vue'
import { useI18n } from 'vue-i18n'
import { Delete, Plus, Edit, Download, CaretLeft, View, Operation } from '@element-plus/icons-vue'
import { ElButton, ElMessageBox, ElMessage, ElSwitch } from 'element-plus'
import { useRouter } from 'vue-router'
import usedicts, { DictDirection } from '@/store/modules/dicts'
import { listJob, delJob, runJob, updateJob } from '@/api/monitor/job'

const setForm = defineAsyncComponent(() => import('./components/setForm.vue'))
const dicts = usedicts()
const { t } = useI18n()
const routers = useRouter()
defineProps({
  modelValue: {
    type: Number,
  },
})
const
  title = ref(''),
  open = ref(false),
  single = ref(true),
  multiple = ref(true),
  // 任务日志详细
  openView = ref(false),
  labelPosition = ref('right'),
  // 查询参数
  queryParams = ref({
    pageNum: 1,
    pageSize: 10,
  }),
  // 任务日志详细
  formDetail = ref({
    jobId: undefined,
    jobName: undefined,
    createTime: undefined,
    cronExpression: undefined,
    nextValidTime: undefined,
    invokeTarget: undefined,
    misfirePolicy: undefined,
  }),
  customContainerRef = ref(null),
  setFormRef = ref(null),
  {
    proxy,
  }:{
   proxy:any
 } = getCurrentInstance()
const jobGroupFormat = (row) => dicts.getDictLabel({ dict: DictDirection.任务分组, value: row.jobGroup })
const jobStatusFormat = (row) => dicts.getDictLabel({ dict: DictDirection.任务状态, value: row.status })
const jobConcurrentFormat = (row) => dicts.getDictLabel({ dict: DictDirection.是否并发, value: row.concurrent })
const jobMisfirePolicyFormat = (row) => dicts.getDictLabel({ dict: DictDirection.执行策略, value: row.misfirePolicy })
let ids = []
const emit = defineEmits(['update:modelValue'])
// // 列表选择
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  ids = rows.map(item => item.jobId)
  single.value = rows.length != 1
  multiple.value = !rows.length
}
const handleQuery = () => {
  customContainerRef.value.getList()
}
/** 新增按钮操作 */
const handleAdd = () => {
  open.value = true
  title.value = '添加任务'
}
/** 修改按钮操作 */
const handleUpdate = (row: { [key: string]: any }) => {
  const jobId = row.jobId || ids[0]
  const data = { jobId, pageNum: 1, pageSize: 10 }
  open.value = true
  title.value = '修改任务'
  setFormRef.value.getList(data)
}
/** 删除按钮操作 */
const handleDelete = (row:{[key:string]:any}) => {
  const id = row.id || ids
  ElMessageBox.confirm(
    `"是否确认删除用户编号为"${ id }"的数据项?"`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
  .then(() => delJob(id))
  .then((res) => {
    if (res.code === 200) {
      ElMessage.success('删除成功')
      handleQuery()
    } else {
      ElMessage.error(res.msg)
    }
  })
  .catch((error) => {
    if (error == 'cancel') {
      ElMessage.error(error)
    }
  })
}
/* 立即执行一次 */
const handleRun = (row:{[key:string]:any}) => {
  ElMessageBox.confirm(`确认要立即执行一次"${ row.jobName }"任务吗?`).then(() => runJob(row.jobId, row.jobGroup)).then(() => {
    ElMessage.success('执行成功') 
  })
  .catch(() => {})
}
/** 任务详细信息 */
const handleView = (row:{[key:string]:any}) => {
  const data = { jobId: row.jobId, pageNum: 1, pageSize: 10 }
  listJob(data).then(response => {
    formDetail.value = response.data[0]
    openView.value = true
  })
}
/** 导出按钮操作 */
const handleExport = () => {
  proxy.$download('/schedule/job/export', {
    ...queryParams.value,
  }, `job_${ new Date().getTime() }.xlsx`)
}
/** 任务日志列表查询 */
const handleJobLog = (row: { [key: string]: any }) => {
  const jobId = row.jobId || 0
  routers.push({ path: '/monitor/log/index', query: { jobId } })
}
const handleStatusChange = (row: { [key: string]: any }) => {
  const text = row.status == 1 ? '启用' : '停用'
  row.status = row.status === 0 ? 1 : 0
  const data = { jobId: row.jobId, status: row.status }
  ElMessageBox.confirm(`确认要"${ text }"任务编号为"${ row.jobId }"的任务吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => updateJob(data))
  .then((res) => {
    if (res.code == 200) {
      ElMessage.success(`${ text }成功`)
      handleQuery()
    } 
  })
  .catch((error) => {
    if (error === 'cancel') {
      ElMessage.info('取消操作')
      handleQuery()
    }
  })
}
const mianConfig = computed(() => {
  const queryField = 'monitor.job.queryField.'
  const columns = 'monitor.job.columns.'
  const publicKey = 'public.'
  const btns = 'monitor.job.btns.'
  return {
    query: {
      fields: [
        {
          label: t(`${ queryField }jobName`),
          prop: 'jobName',
        },
        {
          label: t(`${ queryField }jobGroup`),
          prop: 'jobGroup',
          type: 'select',
          option: {
            dictInfo: { 
              dict: DictDirection.任务组名, 
            },
          },

        },
        {
          label: t(`${ queryField }status`),
          prop: 'status',
          type: 'select',
          option: {
            dictInfo: {
              dict: DictDirection.任务状态,
            },
          },
        },
      ],
      queryParams: queryParams.value,
    },
    btns: [
      {
        title: t(`${ publicKey }add`),
        icon: Plus,
        type: 'primary',
        onClick: handleAdd,
        directive: [['hasPermi', ['monitor:job:add']]],
      },
      {
        title: t(`${ publicKey }edit`),
        icon: Edit,
        type: 'success',
        disabled: multiple.value,
        onClick: handleUpdate,
        directive: [['hasPermi', ['monitor:job:edit']]],
      },
      {
        title: t(`${ publicKey }del`),
        icon: Delete,
        type: 'danger',
        disabled: multiple.value,
        onClick: handleDelete,
        directive: [['hasPermi', ['monitor:job:remove']]],
      },
      {
        title: t(`${ publicKey }export`),
        icon: Download,
        type: 'warning',
        onClick: handleExport,
        directive: [['hasPermi', ['monitor:job:export']]],
      },
      {
        title: t(`${ publicKey }journal`),
        icon: Operation,
        type: 'info',
        onClick: handleJobLog,
        directive: [['hasPermi', ['monitor:job:query']]],
      },
    ],
    table: {
      columns: [
        { type: 'selection', width: '55', align: 'center' },
        {
          label: t(`${ columns }jobId`),
          prop: 'jobId',
          align: 'center',
          width: '100',
        },
        {
          label: t(`${ columns }jobName`),
          prop: 'jobName',
          align: 'center',
          width: '150',
        },
        {
          label: t(`${ columns }jobGroup`),
          prop: 'jobGroup',
          align: 'center',
          formatter: (row) => dicts.getDictLabel({ dict: DictDirection.任务分组, value: row.jobGroup }),
        },
        {
          label: t(`${ columns }invokeTarget`),
          prop: 'invokeTarget',
          align: 'center',
        },
        {
          label: t(`${ columns }cronExpression`),
          prop: 'cronExpression',
          align: 'center',
        },
        {
          label: t(`${ columns }status`),
          prop: 'status',
          align: 'center',
          formatter: (row) => dicts.getDictLabel({ dict: DictDirection.任务状态, value: row.status }),
          render(h, params) {
            return h(ElSwitch, {
              onClick: () => {
                handleStatusChange(params.row)
              },
              modelValue: params.row.status,
              'onUpdate:modelValue': (value) => {
                emit('update:modelValue', value)
              },
              activeValue: 0,
              inactiveValue: 1,
              activeColor: '#409EFF',
              inactiveColor: '#C0CCDA',
            })
          },
        },
        {
          label: t(`${ columns }operation`),
          prop: 'operation',
          align: 'center',
          showOverflowTooltip: false,
          className: 'custormFixedCol',
          width: '300',
          fixed: 'right',
          render: (h, params) => {
            const buttons = [
              {
                title: t(`${ publicKey }edit`),
                icon: Edit,
                clickFun: handleUpdate,
                directive: [['hasPermi', ['monitor:job:edit']]],
              },
              {
                title: t(`${ btns }caretRight`),
                icon: CaretLeft,
                clickFun: handleRun,
                directive: [['hasPermi', ['monitor:job:changeStatus']]],
              },
              {
                title: t(`${ btns }view`),
                icon: View,
                clickFun: handleView,
                directive: [['hasPermi', ['monitor:job:query']]],
              },
            ]
            return buttons.map((el) => h(
              ElButton,
              {
                text: true,
                type: 'primary',
                icon: el.icon,
                onClick: () => {
                  el.clickFun(params.row)
                },
              },
              {
                default: () => el.title,
              },
            ))
          },
        },
      ],
      event: {
        onSelectionChange: (rows) => {
          handleSelectionChange(rows)
        },
      },
    },
    api: listJob,
    customKey: 'system/monitor/job',
  }
})

</script>